<template>
  <van-nav-bar left-text="返回" left-arrow @click-left="getTop"/>
  <van-form ref="form">
    <h3>用户注册</h3>
    <van-cell-group inset>
      <van-field
          v-model="form.userName"
          name="用户名"
          label="用户名"
          placeholder="用户名"
          :rules="rules.userName"
      />
      <van-field
          v-model="form.password"
          type="password"
          name="密码"
          label="密码"
          placeholder="密码"
          :rules="rules.password"
      />
      <van-field
          v-model="form.aPassword"
          type="password"
          name="确认密码"
          label="确认密码"
          placeholder="确认密码"
          :rules="rules.aPassword"
      />
    </van-cell-group>
    <div style="margin: 16px">
      <van-button
          round
          block
          type="primary"
          native-type="submit"
          @click="onSubmit(form)"
      >
        注册
      </van-button>
    </div>
  </van-form>
</template>

<script>
import {register} from "../api/user";
import {showToast} from "vant";

export default {
  data() {
    return {
      form: {},
      rules: {
        userName: [{required: true, message: "用户名不得为空!"}],
        password: [
          {required: true, message: "密码不得为空!"},
          {
            required: true,
            validator: (val) => {
              if (val.length < 6 || val.length > 12) {
                return "密码长度介于6~12位之间";
              }
            },
          },
        ],
        aPassword: [
          {required: true, message: "第二次密码不得为空!"},
          {
            required: true,
            validator: (value) => {
              if (value !== this.form.password) {
                return "两次输入密码不一致!";
              }
            },
          },
        ],
      },
    };
  },
  created() {
  },
  methods: {
    onSubmit(user) {
      this.$refs.form
          .validate()
          .then(() => {
            register(user.userName, user.password).then((req) => {
              if (req.data.success) {
                showToast("注册成功!请登录!");
                this.$router.push({name: "login"});
              } else {
                showToast(`${req.data.message}`);
              }
            });
          })
          .catch(() => {
            return false;
          });
    },
    //返回上一级
    getTop() {
      this.$router.back();
      console.log("返回");
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },
};
</script>

<style>
</style>